package com.cy.tool;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;

public class MyFilter extends StrutsPrepareAndExecuteFilter {
	@SuppressWarnings("deprecation")
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {

		// 

		HttpServletRequest request = (HttpServletRequest) req;

		String uri = request.getServletPath();
		Object obj = request.getSession().getValue("user");

	 
		if (obj == null 
				&& (uri.indexOf("isndex") > -1 //未登录不能访问的页面
				)) {
			toLogin((HttpServletRequest) req, (HttpServletResponse) res);
			return;
		}

		 

		HttpServletResponse response = (HttpServletResponse) res;
		String str = request.getServletPath();
		if (request.getServletPath().equals("/fckeditor/editor/filemanager/connectors")) {
			chain.doFilter(request, response);
		} else {

			try {
				prepare.setEncodingAndLocale(request, response);
				prepare.createActionContext(request, response);
				prepare.assignDispatcherToThread();
				if (excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {
					chain.doFilter(request, response);
				} else {
					request = prepare.wrapRequest(request);
					ActionMapping mapping = prepare.findActionMapping(request, response, true);
					if (mapping == null) {
						boolean handled = execute.executeStaticResourceRequest(request, response);
						if (!handled) {
							chain.doFilter(request, response);
						}
					} else {
						execute.executeAction(request, response, mapping);
					}
				}
			} finally {
				prepare.cleanupRequest(request);
			}
		}
	}

	public void toLogin(HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		String path = request.getContextPath();

		String url = request.getRequestURL().toString();
//				+ (request.getQueryString()) != null ? "?"
//						+ request.getQueryString() : "");

		String redirectPageUrl = path + url;
		response.sendRedirect(redirectPageUrl);

		return;
	}

	public void noP(HttpServletRequest request, HttpServletResponse response) throws IOException {

		String path = request.getContextPath();

		String redirectPageUrl = path + "/common/Redirect.jsp?Action=";

		response.sendRedirect(redirectPageUrl);
	}

}
